<template>
  <div :class="$style.wrap">
    <ContentWrap>
      <FormContainer :column="4">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="90px">
          <el-form-item prop="customerType" label="客户类型">
            <el-select v-model="formData.customerType" clearable filterable>
              <el-option v-for="(c,i) in cTypeList" :key="i" :label="c.label" :value="c.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="state" label="任务状态">
            <CustomDictSelect
              placeholder="请选择任务状态"
              dict-type-code="KQ_TASK_STATUS"
              bind-name="dictName"
              bind-value="dictCode"
              :echo-value.sync="formData.state"
              clearable
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item prop="careItem" label="关怀项目">
            <CustomDictSelect
              placeholder="请选择关怀项目"
              dict-type-code="KQ_CARE_ITEM"
              bind-name="dictName"
              bind-value="dictCode"
              :echo-value.sync="formData.careItem"
              clearable
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item prop="customerName" label="客户姓名">
            <el-input v-model="formData.customerName" placeholder="请输入客户姓名" clearable></el-input>
          </el-form-item>
          <el-form-item prop="agreedCareDate" label="预约关怀日期" :span="24/4*1.5">
            <el-date-picker v-model="formData.agreedCareDate" type="daterange" opt placeholder="选择预约关怀日期" clearable></el-date-picker>
          </el-form-item>
          <el-form-item prop="careDate" label="实际关怀日期" :span="24/4*1.5">
            <el-date-picker v-model="formData.careDate" type="daterange" opt placeholder="选择实际关怀日期" clearable></el-date-picker>
          </el-form-item>
          <el-form-item prop="taskCode" label="任务编码" hidden>
            <el-input v-model.trim="formData.taskCode" placeholder="请输入任务编码" clearable />
          </el-form-item>
          <el-form-item prop="careMode" label="关怀方式">
            <CustomDictSelect
              placeholder="请选择关怀方式"
              dict-type-code="CARE_MODE"
              bind-name="dictName"
              bind-value="dictCode"
              multiple
              :echo-value.sync="formData.careMode"
              clearable
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item prop="officeCode" label="办事处">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/office/ref/page"
              placeholder="请选择办事处"
              lable-name="name"
              value-name="code"
              method="get"
              :value.sync="formData.officeCode"
              clearable
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="disCode" label="MSC客户编码">
            <el-input v-model.trim="formData.disCode" placeholder="请输入MSC客户编码" clearable></el-input>
          </el-form-item>
          <el-form-item prop="disName" label="MSC客户名称">
            <el-input v-model="formData.disName" placeholder="请输入MSC客户名称" clearable></el-input>
          </el-form-item>
          <el-form-item prop="careObject" label="关怀对象">
            <el-input v-model="formData.careObject" placeholder="请输入关怀对象" clearable></el-input>
          </el-form-item>
          <el-form-item prop="careObjectPhone" label="关怀电话">
            <el-input v-model="formData.careObjectPhone" number placeholder="请输入关怀电话" clearable></el-input>
          </el-form-item>
          <!-- <el-form-item prop="callOutPhone" label="呼出电话">
            <el-input v-model="formData.callOutPhone" number placeholder="请输入呼出电话" clearable></el-input>
          </el-form-item> -->
          <el-form-item prop="handler" label="分配坐席">
            <StaffSearch v-model="formData.handler" :name.sync="handerName" placeholder="请选择分配坐席" clearable></StaffSearch>
          </el-form-item>
          <el-form-item prop="groupNo" label="创建人业务组">
            <SearchSelectPicker
              url="/call-center/api/v1/businessGroup/"
              placeholder="请选择创建人业务组"
              lable-name="groupName"
              value-name="groupNo"
              method="get"
              :value.sync="formData.groupNo"
              :remote="false"
              filterable
              clearable
              @selectChange="handlerSelectChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="createBy" label="创建人">
            <StaffSearch v-model="formData.createBy" placeholder="请选择创建人" :params="{ query, type: 0 }" clearable></StaffSearch>
          </el-form-item>
          <el-form-item more show>
            <Button @click="resetForm">重置</Button>
            <Button type="primary" enter @click="queryHandle">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="button-container" style="padding-top:0">
        <Add text="新增顾客任务" title="新增顾客任务" @refresh="refresh"></Add>
        <Button type="primary" @click="addMerchantTask">新增商家任务</Button>
        <SeatChange :selected="tableSelected" @refresh="refresh('onPage')"></SeatChange>
        <Button type="primary" @click="genNextMonthCareTask">生成下月关怀任务</Button>
        <CustomMouth></CustomMouth>
        <ExportPane :table-config="tableConfig" :data-source="tableSelected" :export-file="postExport" :query-data-fun="queryHandle" filename="任务管理">导出</ExportPane>
        <Button type="primary" @click="closeCareTask">关闭</Button>
      </div>
      <table-box
        ref="table"
        no-request
        :table-config="tableConfig"
        :other-filters="otherFilters"
        :other-raw="otherRaw"
        @selection-change="(val)=>{tableSelected = val}"
      >
        <el-table-column slot="before" type="selection" align="center" width="40" />
      </table-box>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import CustomDictSelect from '@/components/CustomDictSelect'
import StaffSearch from '@/components/StaffSearch'
import Add from './components/add'
import SeatChange from './components/seatChange'
import CustomMouth from './components/customMouth'
import ExportPane from '@/components/ExportPane'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import { ccDict } from '@/api/dataDict'
import { ArrayFormat } from '@/utils/params-format'
import { deepCopy, parseTime, date24, pageRequsetBody } from '@/utils'
import { postDealerNextMonthCareTask, careTaskCloseBatch, postExport } from '@/api/guestCare'
import { mapGetters } from 'vuex'
export default {
  name: 'TaskManage',
  components: {
    ContentWrap,
    FormContainer,
    CustomDictSelect,
    StaffSearch,
    Add,
    SeatChange,
    ExportPane,
    SearchSelectPicker,
    CustomMouth
  },
  data() {
    return {
      formData: {
        customerType: 1,
        taskCode: '',
        state: '',
        careItem: '',
        careMode: '',
        officeCode: '',
        customerName: '',
        disCode: '',
        disName: '',
        careObject: '',
        careObjectPhone: '',
        // callOutPhone: '',
        handler: '',
        createBy: '',
        groupNo: '',
        agreedCareDate: [],
        careDate: []
      },
      formRules: {},
      cTypeList: [
        {
          value: 1,
          label: '商家'
        },
        {
          value: 2,
          label: '顾客'
        }
      ],
      // table-box
      tableConfig: {
        interfacePath: '/call-center/api/v1/careTask/page',
        pageSize: 10,
        pageFlag: true,
        hideFuncBar: true,
        sort: 'createTime',
        order: 'desc',
        // 表格字段动态配置
        setting: [
          {
            prop: 'index',
            label: '序号',
            width: 80,
            align: 'center',
            formatData: (val) => { return val.keyIndex + 1 }
          },
          {
            prop: 'customerType',
            label: '客户类型',
            width: 120,
            formatData: v => {
              v = v.customerType
              for (const item of this.cTypeList) {
                if (item.value === v || item.value.toString() === v) {
                  return item.label
                }
              }
              return ''
            }
          },
          {
            prop: 'taskCode',
            label: '任务编码',
            className: 'table-click-text',
            isButton: true,
            width: 185,
            clickFun: (row) => {
              this.taskDetail(row, 'preview')
            }
          },
          {
            prop: 'handler',
            label: '分配坐席',
            width: 100,
            formatData: (val) => {
              if (!val.handler) {
                return ''
              }
              return `${val.handlerName}(${val.handler})`
            }
          },
          {
            prop: 'state',
            label: '任务状态',
            width: 100,
            propEnum: {
              appCode: 'call-center',
              domainCode: 'marketing',
              dictTypeCode: 'KQ_TASK_STATUS'
            }
          },
          {
            prop: 'careItem',
            label: '关怀项目',
            width: 100,
            formatData: (val) => {
              if (val.careItem === undefined || val.careItem === null) {
                return ''
              }
              const careItem = val.careItem.toString().split(',') || []
              const str = []
              this.careItemList.map(list => {
                careItem.forEach(item => {
                  if (Number(list.dictCode) === Number(item)) {
                    str.push(list.dictName)
                  }
                })
              })
              return str.join(',')
            }
          },
          {
            prop: 'agreedCareDate',
            label: '预约关怀日期',
            width: 140
          },
          {
            prop: 'careObject',
            label: '关怀对象',
            width: 120
          },
          {
            prop: 'careObjectPhone',
            label: '关怀电话',
            width: 120
          },
          {
            prop: 'workOrderCode',
            label: '工单编号',
            width: 160
          },
          // {
          //   prop: 'workOrderCodeSeat',
          //   label: '工单坐席',
          //   width: 120
          // },
          {
            prop: 'officeName',
            label: '办事处',
            width: 120
          },
          {
            prop: 'disName',
            label: '经销商',
            width: 120
          },
          {
            prop: 'shopName',
            label: '门店',
            width: 120
          },
          {
            prop: 'satisfaction',
            label: '满意度评价',
            width: 120,
            propEnum: {
              appCode: 'call-center',
              domainCode: 'marketing',
              dictTypeCode: 'KQ_SATISFACTION'
            }
          },
          {
            prop: 'remarks',
            label: '备注',
            width: 160
          },
          {
            prop: 'createBy',
            label: '创建人',
            width: 160,
            formatData: v => {
              return `${v.createByName || '--'}(${v.createBy || '--'})`
            }
          },
          {
            prop: 'creatorBusinessGroupName',
            label: '创建人业务组',
            width: 160
          },
          {
            prop: 'createTime',
            label: '创建时间',
            width: 140
          },
          {
            prop: '',
            label: '最后修改人',
            width: 160,
            formatData: v => `${v.lastUpdateByName || '--'}(${v.lastUpdateBy || '--'})`
          },
          {
            prop: 'lastUpdateTime',
            label: '最后修改时间',
            width: 140
          },
          {
            label: '操作',
            width: 80,
            fixed: 'right',
            align: 'center',
            button: [{
              name: '处理',
              clickFun: (val) => {
                // const state = val.state
                // if (state === 4 || state === '4') {
                //   this.$message.info('任务已关闭！')
                //   return
                // }
                this.taskDetail(val, 'handle')
              },
              className: 'table-handelclick-text'
            }]
          }
        ]
      },
      tableSelected: [],
      otherFilters: [],
      careItemList: [],
      otherRaw: {},
      // 是否已创建
      visit: false,
      // 坐席名称
      handerName: ''
    }
  },
  computed: {
    ...mapGetters(['accountNo', 'staffName']),
    query() {
      return this.formData.groupNo ? { groupNo: { value: this.formData.groupNo, operator: 'like' }} : null
    }
  },
  watch: {
    accountNo: {
      handler(v) {
        this.$set(this.formData, 'handler', v)
        this.handerName = this.staffName
      },
      immediate: true
    },
    'formData.customerType': {
      handler(v) {
        this.$nextTick(() => {
          this.setHandler(v)
        })
      },
      immediate: true
    }
  },
  created() {
    this.getDict()
  },
  activated() {
    if (this.visit) {
      this.queryHandle()
    }
  },
  methods: {
    queryHandle(type) {
      return this.$refs.form.validate().then(() => {
        this.visit = true
        const data = deepCopy(this.formData)
        const groupNo = data.groupNo
        delete data.groupNo
        const formatData = `{y}-{m}-{d}`
        if (data.agreedCareDate instanceof Array && data.agreedCareDate.length === 2) {
          data.agreedCareDate[0] = parseTime(data.agreedCareDate[0], formatData)
          data.agreedCareDate[1] = parseTime(date24(data.agreedCareDate[1]), formatData)
        }
        if (data.careDate instanceof Array && data.careDate.length === 2) {
          data.careDate[0] = parseTime(data.careDate[0], formatData)
          data.careDate[1] = parseTime(date24(data.careDate[1]), formatData)
        }
        if (data.careMode instanceof Array && data.careMode.length > 0) {
          data.careMode = `[${data.careMode.join(',')}]`
        }

        const operator = {}
        const e = ['customerType', 'taskCode', 'state', 'careItem', 'officeCode', 'disCode', 'careObjectPhone', 'callOutPhone', 'handler', 'createBy', 'disCode']
        e.forEach(e => { operator[e] = '=' })
        operator.careMode = 'in'
        operator.agreedCareDate = ['>=', '<']
        operator.careDate = ['>=', '<']

        this.otherRaw = { businessGroupNo: groupNo } // businessGroupNos 多选
        this.otherFilters = ArrayFormat(data, operator)
        if (type !== 'export') {
          this.refresh()
        }
        return this.otherFilters // 导出用
      })
    },
    // 重置
    resetForm() {
      this.$refs.form.resetFields()
      this.setHandler()
    },
    taskDetail(row, type) {
      // 还要区分商家顾客
      let name = ''
      let title = ''
      if (type === 'handle') {
        if (row.customerType === 1 || row.customerType === '1') {
          name = 'MerchantHander'
          title = '商家任务处理'
        } else {
          title = '顾客任务处理'
          name = 'CustomerHander'
        }
      } else {
        if (row.customerType === 1 || row.customerType === '1') {
          title = '商家任务详情'
          name = 'MerchantDetail'
        } else {
          title = '顾客任务详情'
          name = 'CustomerDetail'
        }
      }
      this.$router.push({ name, query: { id: row.id, title }})
    },
    getDict() {
      ccDict('KQ_CARE_ITEM').then(res => {
        this.careItemList = res.data
      })
    },
    // 生成下月关怀任务
    genNextMonthCareTask() {
      return this.$msgbox({
        title: '生成下月关怀任务',
        type: 'warning',
        message: '确认生成下月关怀任务？',
        showCancelButton: true
      }).then(() => {
        return postDealerNextMonthCareTask().then(res => {
          this.$message.success(`任务生成成功，共${res.data}条！`)
        })
      })
    },
    // 关闭任务
    closeCareTask() {
      if (this.tableSelected.length <= 0) {
        this.$message.info('请选择要关闭的任务！')
        return
      }
      if (this.tableSelected.some(e => {
        return e.state === 3 || e.state === '3' || e.state === 4 || e.state === '4'
      })) {
        this.$message.info('选中数据包含已关闭或已关怀任务！')
        return
      }
      return this.$msgbox({
        title: '关闭任务',
        type: 'warning',
        message: '确认关闭关怀任务？',
        showCancelButton: true
      }).then(() => {
        return careTaskCloseBatch(this.tableSelected.map(e => e.id)).then(res => {
          this.$message.success('关闭成功！')
          this.refresh()
        })
      })
    },
    refresh(onPage) {
      this.$nextTick(() => {
        this.$refs.table.initTableData(onPage)
      })
    },
    // 新增商家任务
    addMerchantTask() {
      this.$router.push({ name: 'AddMerchant' })
    },
    // 导出
    postExport() {
      return this.queryHandle('export').then(data => {
        const body = {
          pageFlag: true,
          filtersRaw: data,
          paramsRaw: this.otherRaw,
          rows: 10000,
          page: 1
        }
        return postExport(pageRequsetBody(body))
      })
    },
    // 设置分配坐席默认值
    setHandler(v) {
      if (v === undefined) {
        v = this.formData.customerType
      }
      if (v === 1) {
        this.$set(this.formData, 'handler', this.accountNo)
        this.handerName = this.staffName
      } else if (v === 2) {
        this.$set(this.formData, 'handler', '')
        this.handerName = ''
      }
    },
    handlerSelectChange(v) {
      this.$set(this.formData, 'createBy', '')
    }
  }
}
</script>
<style lang='scss' module>
.wrap{

}
</style>
